﻿using Chemistry.Models;
using Chemistry.Tools;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chemistry.ViewModels
{
    public class SelectQuetionViewModel : VmBase
    {
        private bool _canCommit;

        private ObservableCollection<ExaminationPoint> _points;
        public ObservableCollection<ExaminationPoint> Points
        {
            get { return _points; }
            set { _points = value; RaisePropertyChanged("Points"); }
        }

        public SelectQuetionViewModel()
        {
            CommitCommand = new GalaSoft.MvvmLight.Command.RelayCommand(CommitExec,  CanCommit);
            InitMessage();
        }

        private bool CanCommit()
        {
            if (this.Points == null || this.Points.Count <= 0 || !_canCommit)
            {
                return false;
            }
            var checkcount = this.Points.Count(i => i.IsChecked);
            return checkcount > 2;//3题才可以考试
        }

        private void InitMessage()
        {
            Register<string>(
                this,
                MessageToken.SelectQuestion,
                (i) =>
                    {
                        _canCommit = true;
                        IsOpen = true;
                        GetServerPoints(i);
                    });

            Register<List<ExaminationPoint>>(
                this,
                MessageToken.CheckSelectedQuestion,
                (i) =>
                {
                    _canCommit = false;
                        IsOpen = true;
                        this.Points = new ObservableCollection<ExaminationPoint>(i);
                    });
        }

        private void CommitExec()
        {
            IsOpen = false;
            Send<List<ExaminationPoint>>(this.Points.ToList(), MessageToken.ShowInputNumber);
            Send(MessageToken.ShowInputNumber);
        }

        private async void GetServerPoints(string classname)
        {
            var points = await GetPointsByClassName(classname);
            this.Points = points != null ? new ObservableCollection<ExaminationPoint>(points) : new ObservableCollection<ExaminationPoint>();
        }

        private async Task<List<ExaminationPoint>> GetPointsByClassName(string calssname)
        {
            List<ExaminationPoint> points = null;
            try
            {
                string request_url = string.Format("{0}/GetPointsByClassname?classname={1}", workflow_url, calssname);
                var result = await HttpBaseChemistry.GetAsync<ExamPointApiModel>(request_url);
                if (result != null && result.status == 0)
                {
                    points = result.points;
                }
            }
            catch (Exception ex)
            {
                AppendExecptionAsync(ex);
            }
            return points;
        }
    }
}
